$(function(){
    new Vue({
        el: "#right",
        data:{
            module:"",
            itemId:"",
            check: false,
            form_data:{
                ClassId: "",
                Name: "",                           //标题名称
                Description: "",                     //描述
                Keywords: [],
                Source: "",                          //来源作者或者机构
                Type: 1,                             //1.网站内容,2广告
                ContentUrl: "",                        //内容
                Style: 1,                            //样式
                State: 0,                        //是否发布  false 0 未发布  true 1 已发布  2 取消发布
                PhotoUrl: ["","",""],                    //图片数组
                content: "",
            },
            keywords: "",
            isIE:''

        },
        created:function() {
            this.isIE = /msie/i.test(navigator.userAgent) && !window.opera;
            if(header.GetQueryString("classId") != null){
                this.form_data.ClassId = header.GetQueryString("classId");
            }
            if(header.GetQueryString("itemId") != null ) {
                this.itemId = header.GetQueryString("itemId");
                this.get_info_id();
                $('#right').find('.ui.form').find("input[type='radio']").attr('disabled','true');
            }
            this.get_model_name();
        },
        watch: {
            "check" : function() {
                if(this.check == true) {
                    this.form_data.State = 1;
                }else {
                    this.form_data.State = 0;
                }
            },
            "form_data.State" : function() {
                if(this.form_data.State == 1) {
                    this.check = true;
                }
            }
        },
        methods: {
            /** 创建或者更新 **/
            save: function () {
                var self = this;
                var Data = {};
                var url =  rootPath + "/content/create-dynamic-find";
                if(self.itemId != "") {
                    url = rootPath + "/content/update-dynamic-find";
                    Data["obj.Id"] = self.itemId;
                }
                if(self.form_data.ClassId =="" || self.form_data.Name =="" || self.form_data.Description =="") {
                    header.Popup("alert","某些必填数据为空!!!!","");
                } else {
                    for(var  key in  self.form_data) {
                        if(key == "PhotoUrl" ) {
                            for(var i=0; i < self.form_data[key].length; i++) {
                                if(self.form_data[key][i] != ""){
                                    Data["obj."+key+"["+i+"]"]  = self.form_data[key][i];
                                }
                            }
                            delete i;
                        }else if(key == "Keywords") {
                            for(var i=0; i < self.form_data[key].length; i++) {
                                if(self.form_data[key][i] != ""){
                                    Data["obj."+key+"["+i+"]"]  = self.form_data[key][i];
                                }
                            }
                            delete i;
                        } else {
                            Data["obj."+key] = self.form_data[key];
                        }
                    }
                    delete key;
                    console.log(Data);
                    $.ajax({
                        url : url,
                        type: 'POST',
                        data: Data,
                        dataType: "json",
                        success: function(result) {
                            if(result.status) {
                                header.Popup("alert",result.data,function(){
                                    window.location.reload();
                                });
                            } else {
                                header.Popup("alert",result.error,"");
                            }
                        }
                    });
                }
            },
            /** 获取栏目表 **/
            get_model_name: function() {
                var self = this;
                $.ajax({
                    url: rootPath+'/content/find-model-name',
                    type : 'get',
                    dataType: "json",
                    success: function (result) {
                        if(result.status) {
                            self.module = result.data.items;
                        }else {
                            header.Popup("alert",result.error,"");
                        }
                    }
                });
            },
            /** 清除图片 **/
            clear: function(element) {
                var count = element.split("_")[2] - 1;
                var self = this;
                $.ajax({
                    url: rootPath+"/img/delete",
                    type: "get",
                    data: {
                        img_url: self.form_data.PhotoUrl[count].substr(1)
                    },
                    dataType: "json",
                    success: function (data) {
                        $('#'+element).val("");
                        Vue.set(self.form_data.PhotoUrl,count,"");
                        header.Popup("alert",data.msg,"");
                    }
                });
            },
            /** 选择图片**/
            img_select: function(element) {
                $('#'+element).click();
            },
            /** 获取图片流 **/
            img_change: function(e) {
                e = e || window.event;
                var obj = e.target || e.srcElement;
                var imgSize = 0;
                var reader = new FileReader();
                if (this.isIE && !obj.files) {
                    var filePath = obj.value;
                    var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
                    var file = fileSystem.GetFile(filePath);
                    imgSize = file.Size;
                } else {
                    imgSize = obj.files[0].size;
                }
                if ((imgSize / 1024) > 5000) {
                    header.Popup("alert","附件不能大于5M","");
                    obj.value = "";
                    return  false;
                }
                var name = obj.value;
                var fileName = name.substring(name.lastIndexOf(".") + 1).toLowerCase();
                if (fileName != "jpg" && fileName != "jpeg" && fileName != "pdf" && fileName != "png" ) {
                    header.Popup("alert","请选择图片格式文件上传(jpg,png,gif,gif等)！","");
                    obj.value = "";
                    return
                }
                reader.readAsDataURL(obj.files[0]);
                reader.onload = function (event) {
                    obj.parentElement.previousElementSibling.querySelector("img").src = reader.result;
                };
            },
            /** 图片上传 **/
            img_upload: function(fileElementId) {
                var self = this;
                var count = fileElementId.split("_")[2] - 1;
                if($('#'+fileElementId).val() == ""){
                    header.Popup("alert","上传图片不能为空!!!!","");
                    return ;
                }
                var img_url = "&img_url=" + (self.form_data.PhotoUrl[count] == "" || typeof self.form_data.PhotoUrl[count] == "undefined" ?
                                "" :  self.form_data.PhotoUrl[count].substr(1));
                $.ajaxFileUpload({
                    url: rootPath+'/img?img_id='+fileElementId+img_url,
                    secureuri: false,
                    fileElementId: fileElementId,
                    type:'post',
                    success: function(result) {
                        var dataStr = $(result).find("body").text();//获取返回的字符串
                        var dataJson = $.parseJSON(dataStr);//把字符串转化为json对象
                        if(dataJson.status) {
                            var callback = function() {
                                Vue.set(self.form_data.PhotoUrl,count,dataJson.data.path.replace(/\\/g, "/"));
                                $('#'+fileElementId).change(self.img_change);
                            };
                            header.Popup("alert","上传成功",callback);
                        } else {
                            header.Popup("alert",dataJson.error,"");
                        }
                    }
                });
            },
            /** 根据id获取所有信息**/
            get_info_id: function(id) {
                var self = this;
                $.ajax({
                    url : rootPath + "/content/get-dynamic-find-by-id",
                    type: 'get',
                    data: {
                        id: this.itemId
                    },
                    dataType: "json",
                    success: function(result) {
                        if(result.status) {
                            for(var key in result.data) {
                                if(key != "id" && key != "classId"){
                                    if(key == "keywords") {
                                        for(var i=0; i<result.data[key].length; i++) {
                                            self.form_data[key.substr(0,1).toUpperCase() + key.substr(1)].push(result.data[key][i]);
                                        }
                                        delete i;
                                    }  else if(key == "photoUrl") {
                                        for(var i=0; i<3; i++) {
                                            Vue.set(self.form_data.PhotoUrl,i,typeof result.data[key][i] == "undefined" ? "":result.data[key][i]);
                                            console.log(self.form_data.PhotoUrl[i]);
                                        }
                                        delete i;
                                    } else {
                                        self.form_data[key.substr(0,1).toUpperCase() + key.substr(1)] = result.data[key];
                                    }
                                }
                            }
                            delete key;
                            if(self.form_data.ContentUrl != "") {
                                self.getContent();
                            }
                        } else {
                            header.Popup("alert",result.error,"");
                        }
                    }
                });
            },
            /** 图片地址转化 **/
            imgUrl: function(url) {
                return rootPath + (typeof url == "undefined" ||  url == ""?  "/common/img/white.jpg" :  url);
            },
            /** 读取文件内容 **/
            getContent: function() {
                var self = this;
                $.ajax({
                    url: rootPath + "/html/read",
                    type: 'get',
                    data: {
                        html_url : self.form_data.ContentUrl.substr(1)
                    },
                    dataType: 'json',
                    success: function(result){
                        if(result.status) {
                            self.form_data.content = result.data;
                        }else {
                            header.Popup("alert","读取文件失败","");
                        }
                    }
                });
            },
            /** 关键字 **/
            onEnter: function() {
                if(this.form_data.Keywords.indexOf(this.keywords) >= 0) {
                    header.Popup("alert","关键词已存在","");
                } else if (this.keywords == "") {
                    header.Popup("alert","填写内容为空","");
                } else {
                    this.form_data.Keywords.push(this.keywords);
                }
                this.keywords = "";
            },
            /** 图片不存在时 **/
            imgError: function(count) {
                Vue.set(this.form_data.PhotoUrl,count,"");
            }
        }
    });
});

